<template>
  <div id="found">
    <div class="header">
      <div class="nav-container" ref="navContainer" @touchstart="onDragStart" @touchmove="onDragMove"
        @touchend="onDragEnd" @mousedown="onDragStart" @mousemove="onDragMove" @mouseup="onDragEnd"
        @mouseleave="onDragEnd">
        <ul class="nav-list" :style="{ transform: `translateX(${translateX}px)` }">
          <li v-for="(item, index) in headerList" :key="index" :class="{ active: currentIndex === index }"
            @click="handleNavClick(index, item)" ref="navItems">
            {{ item }}
          </li>
        </ul>
      </div>
      <div class="search-icon" @click="$router.push('/search')">
        <i class="one-icon one-icon-search"></i>
      </div>
    </div>

    <router-view />

    <div class="search-page">

    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      headerList: ["阅读", "日签", "专题", "问答", "长篇", "小记", "热榜", "书影", "音乐", "作者"],
      currentIndex: 2, // 默认选中"专题"
      translateX: 0,
      itemWidths: [],
      navListWidth: 0,
      containerWidth: 0,
      itemOffsets: [], // 存储每个导航项的左侧偏移量
      isDragging: false, // 是否正在拖动
      startX: 0, // 拖动起始位置
      startTranslateX: 0, // 拖动开始时的translateX值
      maxTranslateX: 0, // 最大可拖动距离（右边界）
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 获取每个导航项的宽度和偏移量
      this.calculateNavMetrics();

      // 根据路由设置当前激活的导航项
      this.setActiveByRoute();

      // 初始时根据默认选中项调整位置
      this.adjustPosition(this.currentIndex);

      // 计算最大可拖动距离
      this.updateMaxTranslateX();
    });

    // 监听窗口大小变化，重新计算
    window.addEventListener('resize', () => {
      this.$nextTick(() => {
        this.calculateNavMetrics();
        this.adjustPosition(this.currentIndex);
        this.updateMaxTranslateX();
      });
    });
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  created() {
    this.handleResize = () => {
      this.$nextTick(() => {
        this.calculateNavMetrics();
        this.adjustPosition(this.currentIndex);
        this.updateMaxTranslateX();
      });
    };
  },
  methods: {
    onDragStart(event) {
      this.isDragging = true;
      this.startX = event.type.includes('mouse') ? event.clientX : event.touches[0].clientX;
      this.startTranslateX = this.translateX;
    },

    onDragMove(event) {
      if (!this.isDragging) return;

      const currentX = event.type.includes('mouse') ? event.clientX : event.touches[0].clientX;
      const diff = currentX - this.startX;
      let newTranslateX = this.startTranslateX + diff;

      if (newTranslateX > 0) {
        newTranslateX = 0;
      } else if (newTranslateX < this.maxTranslateX) {
        newTranslateX = this.maxTranslateX;
      }

      this.translateX = newTranslateX;

      event.preventDefault();
    },

    onDragEnd() {
      this.isDragging = false;
    },

    updateMaxTranslateX() {
      this.maxTranslateX = Math.min(0, this.containerWidth - this.navListWidth);
    },

    // 计算导航相关的尺寸数据
    calculateNavMetrics() {
      if (!this.$refs.navItems || !this.$refs.navContainer) return;

      // 获取每个导航项的宽度
      this.itemWidths = this.$refs.navItems.map(item => item.offsetWidth);

      // 计算每个导航项的左侧偏移量
      this.itemOffsets = [];
      let offset = 0;
      this.itemOffsets.push(0); // 第一个元素的偏移量为0

      for (let i = 1; i < this.itemWidths.length; i++) {
        offset += this.itemWidths[i - 1];
        this.itemOffsets.push(offset);
      }

      // 计算导航列表总宽度
      this.navListWidth = this.itemWidths.reduce((total, width) => total + width, 0);

      // 获取容器宽度
      this.containerWidth = this.$refs.navContainer.offsetWidth;
    },

    // 根据路由设置激活的导航项
    setActiveByRoute() {
      const path = this.$route.path;
      const routeName = path.split('/').pop();
      const index = this.headerList.findIndex(item => {
        return this.getRouteName(item) === routeName;
      });

      if (index !== -1) {
        this.currentIndex = index;
      }
    },

    // 处理导航项点击
    handleNavClick(index, item) {
      if (this.currentIndex === index) return;

      // 更新当前索引
      this.currentIndex = index;

      // 调整位置
      this.adjustPosition(index);

      // 路由跳转
      const routeName = this.getRouteName(item);
      this.$router.push(`/found/${routeName}`);
    },

    // 调整导航位置
    adjustPosition(index) {
      // 前两个和最后两个项不居中处理
      if (index <= 1 || index >= this.headerList.length - 2) {
        this.handleEdgeItems(index);
      } else {
        // 其他项居中显示
        this.centerItem(index);
      }
    },

    // 处理边缘项（前两个和后两个）
    handleEdgeItems(index) {
      let newTranslateX = 0;

      if (index <= 1) {
        // 前两个项滚动到最左侧
        newTranslateX = 0;
      } else if (index >= this.headerList.length - 2) {
        // 最后两个项滚动到最右侧
        newTranslateX = this.containerWidth - this.navListWidth;
        if (newTranslateX > 0) newTranslateX = 0; // 确保不会出现正值
      }

      this.translateX = newTranslateX;
    },

    // 将指定项居中显示
    centerItem(index) {
      // 计算当前项的中心位置（相对于导航列表）
      const itemCenter = this.itemOffsets[index] + this.itemWidths[index] / 2;

      // 容器的中心位置
      const containerCenter = this.containerWidth / 2;

      // 计算需要的偏移量
      let newTranslateX = containerCenter - itemCenter;

      // 边界检查：不能超过最左侧
      if (newTranslateX > 0) {
        newTranslateX = 0;
      }

      // 边界检查：不能超过最右侧
      const minTranslateX = this.containerWidth - this.navListWidth;
      if (newTranslateX < minTranslateX) {
        newTranslateX = minTranslateX;
      }

      this.translateX = newTranslateX;
    },

    getRouteName(item) {
      // 将导航项名称转换为英文路由名称
      const nameMap = {
        '阅读': 'reading',
        '日签': 'daily-sign',
        '专题': 'topic',
        '问答': 'qa',
        '长篇': 'long-article',
        '小记': 'note',
        '热榜': 'hot-list',
        '书影': 'book-movie',
        '音乐': 'music',
        '作者': 'author'
      };
      return nameMap[item] || item;
    }
  },
  watch: {
    // 监听路由变化，更新激活状态和位置
    $route() {
      this.setActiveByRoute();
      this.adjustPosition(this.currentIndex);
    }
  }
}
</script>

<style src="../assets/icon-style.css"></style>
<style scoped lang="less">
#found {
  width: 100%;
  height: 100vh;
  overflow-x: hidden;
  background-color: #f5f5f5;

  .header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 8vh;
    background-color: #fff;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eee;
    z-index: 10;

    .nav-container {
      flex: 1;
      overflow: hidden;
      height: 100%;

      .nav-list {
        display: flex;
        height: 100%;
        transition: transform 0.3s ease;
        padding: 0;
        margin: 0;
        list-style: none;

        li {
          padding: 0 20px;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 15px;
          color: #333;
          white-space: nowrap;
          cursor: pointer;

          &.active {
            font-size: 17px;
            font-weight: bold;
            color: #000;
          }
        }
      }
    }

    .search-icon {
      width: 50px;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      i {
        font-size: 20px;
        color: #333;
      }
    }
  }
}
</style>
